<?php

namespace App\Http\Controllers\Admin\Finance;

use App\Http\Controllers\Controller;
use App\Models\Order;
use App\Models\UserInvoice;
use App\Traits\Controllers\IndexTraits;
use App\Traits\Controllers\ShowTraits;
use App\Transformers\Order\OrderTransformer;
use App\Transformers\User\UserInvoicesTransformer;
use Carbon\Carbon;
use Illuminate\Http\Request;

class UserInvoiceController extends Controller
{
    use IndexTraits;
    //详情
    use ShowTraits;

    public $model = UserInvoice::class;

    public $transformer = UserInvoicesTransformer::class;

    /**
     * 发票列表
     */

    public function index(Request $request)
    {
        //先处理传过来的搜索数据
        $this->formatIndexQuery($request);
        //获取开始时间和结束时间
        $start = $request->input('start');
        $stop = $request->input('stop');
        $order_number  =  $request->input('order_number');
        $user_name  =  $request->input('user_name');
        $user_phone  =  $request->input('user_phone');

        $data = $this
            ->getQuery()
            ->whereHas('order', function ($query) use ($start,$stop,$order_number,$user_name,$user_phone) {
                //自定义时间
                if(!empty($start) && !empty($stop)){
                    $query->whereBetween('created_at',[$start,$stop]);
                }

                //搜索订单号
                if(!empty($order_number)){
                    $query->where('order_number',$order_number);
                }

                //搜索用户姓名
                if(!empty($user_name)){
                    $query->where('user_name',$user_name);
                }

                //搜索用户电话号
                if(!empty($user_phone)){
                    $query->where('user_phone',$user_phone);
                }
            })
            ->pimp()//自动转换where条件
            ->paginate($this->getPageLimit());

        return $this->response->paginator($data, resolve($this->transformer));
    }

    /**
     *发票订单详情
     */

    public function show($id)
    {
        $show = $this->getQuery()->where('id',$id)->value('order_id');// findOrFail 查找失败时抛出异常404
        $order = Order::where('id',$show)->get();

        return $this->response->collection($order, new OrderTransformer());
    }
}
